package com.sxkiler.demo.test.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * mongodb默认配置
 */
public class MongoDbConfig implements BaseDbConfig {
    protected String name;
    protected String host;
    protected int port;
    protected String username;
    protected String password;
    protected String database;
    protected String authentication_database;

    public MongoDbConfig(){}
    public MongoDbConfig(String name){this.name = name;}

    @Override
    public boolean isValid() {
        if(ObjectUtil.isAllNotEmpty(name,host,port,username,password)){
            return true;
        }
        return false;
    }

    @Override
    public DBType getDBType(){
        return DBType.MONGODB;
    }

    public MongoDbFactory mongoDbFactory(){
        //构建mongodClient配置
        MongoClientSettings.Builder builder = MongoClientSettings.builder();
        //构建集群配置
        List<ServerAddress> addresses = new ArrayList<ServerAddress>();
        ServerAddress address = new ServerAddress(host,port);
        addresses.add(address);
        builder.applyToClusterSettings(builder1 -> {
            builder1.hosts(addresses);
        });
        //加密配置
        builder.credential(MongoCredential.createCredential(username, authentication_database, password.toCharArray()));
        //创建client
        MongoClient client = MongoClients.create(builder.build());
        return new SimpleMongoClientDbFactory(client,database);
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getDatabase() {
        return database;
    }
    public void setDatabase(String database) {
        this.database = database;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public String getAuthentication_database() {
        return authentication_database;
    }

    public void setAuthentication_database(String authentication_database) {
        this.authentication_database = authentication_database;
    }
}
